import Koa from 'koa'
import json from 'koa-json'
import onError from 'koa-onerror'
import logger from 'koa-logger'
import bodyParser from 'koa-bodyparser'
import cors from 'kcors'
import enforceHttps from 'koa-sslify'

const app = new Koa()

const index = require('./routes/index')
const users = require('./routes/users')
const stream = require('./routes/stream')

// error handler
onError(app)

// middlewares
app.use(enforceHttps())
app.use(bodyParser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(cors())

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(stream.routes(), stream.allowedMethods())

module.exports = app
